#include "server.h"
int main() {
    // 初始化数据库连接
    log_event("SYSTEM", NULL, "Initializing database connection");
    conn = mysql_init(NULL);
    if (!mysql_real_connect(conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, 0, NULL, 0)) {
        fprintf(stderr, "DB Error: %s\n", mysql_error(conn));
        log_event("ERROR", NULL, "Failed to connect to database");
        exit(EXIT_FAILURE);
    }
    log_event("SYSTEM", NULL, "Database connection initialized successfully");

    // 创建TCP套接字
    log_event("SYSTEM", NULL, "Creating TCP socket");
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == -1) {
        perror("Socket creation failed");
        log_event("ERROR", NULL, "Socket creation failed");
        exit(EXIT_FAILURE);
    }
    
    // 设置套接字选项
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("Setsockopt failed");
        log_event("ERROR", NULL, "Setsockopt failed");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in address = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = INADDR_ANY,
        .sin_port = htons(SERVER_PORT)
    };

    // 绑定并监听
    log_event("SYSTEM", NULL, "Binding socket");
    if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) == -1) {
        perror("套接字绑定失败");
        log_event("ERROR", NULL, "套接字绑定失败");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    
    log_event("SYSTEM", NULL, "开始监听端口");
    if (listen(server_fd, MAX_CLIENTS) == -1) {
        perror("监听失败");
        log_event("ERROR", NULL, "监听失败");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    
    printf("✅ 服务器启动，正在监听端口 %d...\n", SERVER_PORT);
    log_event("STARTUP", NULL, "服务器启动并开始监听");

    // 主循环处理客户端连接
    log_event("SYSTEM", NULL, "Entering main loop to handle clients");
    while (1) {
        struct sockaddr_in client_addr;
        socklen_t addr_len = sizeof(client_addr);
        
        log_event("SYSTEM", NULL, "Waiting for client connection");
        int client_sock = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
        if (client_sock == -1) {
            perror("接受连接失败");
            log_event("ERROR", NULL, "接受连接失败");
            continue;
        }
        
        char client_ip[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
        
        // 记录客户端连接
        char connect_msg[100];
        snprintf(connect_msg, sizeof(connect_msg), "Client connected from %s", client_ip);
        log_event("CONNECT", NULL, connect_msg);

        pid_t pid = fork();
        if (pid == 0) {  // 子进程处理客户端
            close(server_fd);
            handle_client(client_sock);
            // if (EXIT_SUCCESS) {
            //     // 在 handle_client 中获取到用户名后记录
            // }
            
            // 记录客户端断开
            char disconnect_msg[100];
            snprintf(disconnect_msg, sizeof(disconnect_msg), "Client disconnected (%s)", client_ip);
            log_event("DISCONNECT", NULL, disconnect_msg);
            
            close(client_sock);
            exit(0);
        } else if (pid < 0) {
            perror("进程创建失败");
            log_event("ERROR", NULL, "进程创建失败");
        }
        close(client_sock);
    }

    mysql_close(conn);
    log_event("SHUTDOWN", NULL, "Database connection closed and server shutdown");
    return 0;
}